package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.system.mapper.SysUserRoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.AlertDataMapper;
import com.zzyl.nursing.domain.AlertData;
import com.zzyl.nursing.service.IAlertDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 报警数据Service业务层处理
 *
 * @author alexis
 * @date 2025-01-15
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private ElderMapper elderMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return alertDataMapper.selectById(id);
    }

    /**
     * 查询报警数据列表
     *
     * @param alertData 报警数据
     * @return 报警数据
     */
    @Override
    public List<AlertData> selectAlertDataList(AlertData alertData) {
        List<AlertData> alertDataList = list();
        // 获取当前登录人id
        Long userId = SecurityUtils.getUserId();
        //PD随身设备英文简写
        List<AlertData> pD = new ArrayList<>();
        //FE固定设备英文简写
        List<AlertData> fE = new ArrayList<>();
        // 根据老人绑定的护理员id过滤出报警数据
        for (AlertData data : alertDataList) {
            // 判断是随身设备还是固定设备
            if (data.getLocationType() == 0) {
                //获取老人绑定的护理员id
                List<Long> nursingId = elderMapper.selectElderByName(data.getAccessLocation());
                nursingId.add(1L);
                if (ObjectUtil.isEmpty(nursingId)) {
                    return null;
                }
                //判断登录人id是否与当前报警数据老人的护理人id相等
                for (Long id : nursingId) {
                    if (userId.equals(id)) {
                        pD.add(data);
                    } else {
                        continue;
                    }
                }

            }
            //判断是否是固定设备
            if (data.getLocationType() == 1) {
                //获取维修人的id
                List<Long> mechanicId = sysUserRoleMapper.selectUserIdByRoleName("维修工");
                if (ObjectUtil.isEmpty(mechanicId)) {
                    return null;
                }
                for (Long mechanic : mechanicId) {
                    if (userId.equals(mechanic)) {
                        fE.add(data);
                    } else {
                        continue;
                    }
                }
            }
        }
        Long idByRole = sysUserRoleMapper.selectUserIdByRole(userId);

        if (idByRole == 1L) {
            return alertDataList;
        }
        if (idByRole == 100L) {
            return pD;
        }
        if (idByRole == 101L){
            return fE;
        }
//        for (AlertData data : alertDataList) {
//            if(idByRole==1L||idByRole==100L){
//                if (data.getLocationType()==0){
//                    return pD;
//                }else if(idByRole==1L||idByRole == 101L) {
//                    return fE;
//                }
//            }
//        }
        
        return null;
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return alertDataMapper.insert(alertData);
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return alertDataMapper.updateById(alertData);
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return alertDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return alertDataMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int outcomeResult(AlertData alertData) {

        // 设置处理人id
        alertData.setUserId(SecurityUtils.getUserId());
        // 设置处理人名称
        alertData.setProcessorName(sysUserRoleMapper.selectIdByName(alertData.getUserId()));
        // 设置处理时间
        AlertData data = alertDataMapper.selectById(alertData.getId());
        LocalDateTime dateTime = data.getCreateTime().toInstant().atZone(ZonedDateTime.now().getZone()).toLocalDateTime();
        if (alertData.getProcessingTime().isBefore(dateTime)) {
            alertData.setProcessingTime(LocalDateTime.now());
        }
        int count=0;
        //设置处理状态
        alertData.setStatus(1);
        AlertData byIdData = getById(alertData.getId());
        List<AlertData> list = list();
        for (AlertData alert : list) {
            String alertTime = alert.getCreateTime().toString();
            String byIdTime = byIdData.getCreateTime().toString();
            if (byIdData.getDeviceName().equals(alert.getDeviceName())&&alertTime.equals(byIdTime)) {
                count=alertDataMapper.updateByID(alert.getId(),alertData.getProcessorId(),alertData.getProcessorName(),alertData.getProcessingResult(),alertData.getProcessingTime(),alertData.getStatus());
            }else{
                continue;
            }
        }

        return count;
    }
}
